import smtplib
from email.mime.text import MIMEText
import  random  

#设置服务器所需信息
#163邮箱服务器地址
def send_codemail(mail_server,mail_user,mail_pass,sender,receiver,message,code):    
    mail_host=mail_server
    send_user=mail_user
    passwd=mail_pass
    send_mail=sender
    receivers=[receiver]
    code=random.randrange(100000,999999)
    message=MIMEText('验证码为:%s'%code,'plain','utf-8')
    # print(message)
    message['Subject'] = '懒人注册'
    message['From'] = sender
    message['To']=receivers[0]
    try:
        smtpObj = smtplib.SMTP() 
        #连接到服务器
        smtpObj.connect(mail_host,25)
        #登录到服务器
        smtpObj.login(mail_user,mail_pass) 
        #发送
        smtpObj.sendmail(
            sender,receivers,message.as_string()) 
        #退出
        smtpObj.quit() 
        print( "验证码已经发送,请到邮箱:"+message['To']+"查看验证码:"+str(code))
        return code
    except smtplib.SMTPException as e:
        print('error',e) #打印错误

if __name__ == '__main__':
    
    mail_host = 'smtp.126.com'

    #163用户名
    mail_user = 'wuqing198010'  
    #密码(部分邮箱为授权码) 
    mail_pass = 'XNPGDVUVOMYHIDKE'   
    #邮件发送方邮箱地址
    sender = 'wuqing198010@126.com'  
    #邮件接受方邮箱地址，注意需要[]包裹，这意味着你可以写多个邮件地址群发
    receiver = 'wuqing5156@qq.com' 
    msg=[]
    code=0
    #设置email信息
    #邮件内容设置
    # message = MIMEText('验证码为:%s'%comfirm_code,'plain','utf-8')
    res=send_codemail(mail_host,mail_user,mail_pass,sender,receiver,msg,code=code)
    print(code)
# #邮件主题       
# message['Subject'] = '懒人注册' 
# #发送方信息
# message['From'] = sender 
# #接受方信息     
# message['To'] = receivers[0]  

# #登录并发送邮件
